#!/bin/bash
# reset ldap user's password to uid
#set -x
print_usage() {
    echo "Usage: resetpasswd.sh [options]"
    echo -e "\t -h \t\t\tPrint this message."
    echo -e "\t -u uid\t\t\tSearch by uid."
    echo -e "\t -n name\t\tSearch by name."
    echo -e "\t -p newpasswd\t\tNew password."
}

MAN_DN='cn=Manager,dc=jhc,dc=cn'
#MAN_DN='cn=admin,dc=jhc,dc=cn'
MAN_PASS=ldapsecret78
#MAN_PASS=ldap2013
SEARCH_BASE='ou=people,dc=jhc,dc=cn'
LDAPHOST='10.2.3.66'
#LDAPHOST='localhost'

search_by_uid() {
    search_by_filter "uid=$1"
}

search_by_name(){
    search_by_filter "cn=$1"
}

search_by_filter(){
    tmp_file=$(mktemp)
    ldapsearch -L -h $LDAPHOST -D $MAN_DN -x -w $MAN_PASS -s sub -b $SEARCH_BASE "($1)" 1.1 > $tmp_file
#    cat $tmp_file
    grep '# numEntries: 1' $tmp_file > /dev/null
#    echo "status: $?"
    [ $? -ne 0 ] && exit 1

    grep '^dn: ' $tmp_file | sed 's/^dn: //'
#    while read line ; do
#	if [[ $line =~ ^dn:[[:space:]]+.* ]] ; then
#	    echo ${line#dn: }
#	fi
#    done
    [ -f $tmp_file ] && rm -f $tmp_file
    exit 0
}

while getopts ":u:n:p:h" opt; do
    case $opt in
	u)
	    userdn=$(search_by_uid $OPTARG)
	    if [ $? -ne 0 ] ; then
		echo "search failed."
		exit 1
	    fi ;;
	n)
	    userdn=$(search_by_name $OPTARG)
	    if [ $? -ne 0 ] ; then
		echo "search failed."
		exit 1
	    fi ;;
	p)
	    newpass=$OPTARG ;;
	h|:)
	    print_usage
	    exit 1 ;;
	\?)
	    echo "Unknown option: $OPTARG"
	    exit 1 ;;
    esac
done    

if [ -z $userdn ] ; then
    print_usage
    exit 1
fi

echo "userdn: $userdn"
uid=$(echo ${userdn} | sed  -e 's/^uid=//' -e 's/,.*//')
#if newpass is empty, set newpass as uid
if [ -z $newpass ] ; then
    newpass=$uid
fi
echo "New password: $newpass"
echo 
echo "Before password change."
ldapsearch -LLL -h $LDAPHOST -D $MAN_DN -x -w $MAN_PASS -s sub -b $SEARCH_BASE "(uid=$uid)" userPassword
ldappasswd -h $LDAPHOST -D $MAN_DN -x -w $MAN_PASS -s $newpass $userdn
echo "After password change."
ldapsearch -LLL -h $LDAPHOST -D $MAN_DN -x -w $MAN_PASS -s sub -b $SEARCH_BASE "(uid=$uid)" userPassword
